var AnalysisInit =function(){
	return {
		init:function(){
			AnalysisInit.query();
			AnalysisInit.keyQuery();
			AnalysisInit.reset();
			SystemCommon.getQueryOperation();
			SystemCommon.getQueryEnergy();
			AnalysisInit.getDate();
			AnalysisInit.queryColumn();
			AnalysisInit.changeSelect();
		},
		//条件查询
		query : function(){
			$("#queryAnalysis").on("click","",function(){
				var startTime = new Date($('.detail_datetimeStart').val());
	    		var endTime = new Date($('.detail_datetimeEnd').val());
	    		var day = (endTime.getTime() - startTime.getTime())/(24*60*60*1000);
	    		if (day>720) {
	    			DialogUtil.warning("日期选择范围只能为2年之内");
	    			return false;
	    		}
				if ($("#pictureAnalysis").val() == 0) {
					AnalysisInit.queryColumn();
				}
				if ($("#pictureAnalysis").val() == 1) {
					AnalysisInit.queryElectricPieRate(echarts);
				}
				if ($("#pictureAnalysis").val() == 2) {
					AnalysisInit.queryWaterPieRate(echarts);
				}
				if ($("#pictureAnalysis").val() == 3) {
					AnalysisInit.queryElectricLineColumn(echarts);
				}
				if ($("#pictureAnalysis").val() == 4) {
					AnalysisInit.queryWaterLineColumn(echarts);
				}
			});
		},
		//时间控件
		getDate : function(){
			$('.detail_datetimeStart').val(new Date((new Date().getTime()-365/2 * 24 * 3600 * 1000)).format('yyyy-MM'));
			$('.detail_datetimeEnd').val(new Date().format('yyyy-MM'));
			$('.detail_datetimeStart').datetimepicker({
				format : 'yyyy-mm',
				language : 'zh-CN',
				startView : 'year',
				minView : 'year',
				endDate : new Date(),
				pickerPosition: "bottom-left",
				forceParse : true
			}).on('changeDate', function(ev) {
				var startTime = new Date($('.detail_datetimeStart').val()).getFullYear()+'-'+(new Date($('.detail_datetimeStart').val()).getMonth()+1+1);
				var endTime = new Date($('.detail_datetimeStart').val()).getFullYear()+2+'-'+(new Date($('.detail_datetimeStart').val()).getMonth()+1);
				$('.detail_datetimeEnd').datetimepicker('setStartDate',startTime);
				$('.detail_datetimeEnd').datetimepicker('setEndDate',endTime);
			});
			$('.detail_datetimeEnd').datetimepicker({
				format : 'yyyy-mm',
				language : 'zh-CN',
				pickerPosition: "bottom-left",
				startView : 'year',
				minView : 'year',
//				startDate:new Date(),
				forceParse : true
			}).on('changeDate', function(ev) {
				var startTime = new Date($('.detail_datetimeEnd').val()).getFullYear()-2+'-'+(new Date($('.detail_datetimeEnd').val()).getMonth()+1);
				var endTime = new Date($('.detail_datetimeEnd').val()).getFullYear()+'-'+(new Date($('.detail_datetimeEnd').val()).getMonth());
				$('.detail_datetimeStart').datetimepicker('setStartDate',startTime);
				$('.detail_datetimeStart').datetimepicker('setEndDate',endTime);
			});
		},
		
		//按键触发查询
		keyQuery : function(){
			$(".queryAnalysis").keypress(function (e) {
	            if (e.which == 13) {
	                $("#queryAnalysis").trigger("click");
	            }
	        });
		},
		//重置功能
		reset : function() {
			$("#resetAnalysis").on("click","",function(){
				$(".clearfix input").val("");
				$('.detail_datetimeStart').val(new Date((new Date().getTime()-365/2 * 24 * 3600 * 1000)).format('yyyy-MM'));
				$('.detail_datetimeEnd').val(new Date().format('yyyy-MM'));
				$("#pictureAnalysis").find("option[value='"+0+"']").attr("selected",true);
				$("#analysisCode").each(function(){
					$("#analysisCode").empty();
					$("#analysisCode").append("<option value=''></option>");
					$('#analysisCode').trigger('change.select2');
				});
				$("#operationAnalysis").each(function(){
					$("#operationAnalysis").empty();
					$("#operationAnalysis").append("<option value=''></option>");
					$('#operationAnalysis').trigger('change.select2');
				});
			});
		},
		//查询所有的工序信息
		getOperation : function(){
			$.ajax({
				url: ctx +'/system/operation/listAllOperation/get.mvc',
			    type:"post", 
			    dataType:'json',
			    data : '',
			    success : function(data){
		    		for (var i = 0; i < data.length; i++) {
			    		 $("#operationAnalysis").append("<option value='"+data[i].pkId+"' >" + data[i].name + "</option>");
			    	 };
			    },
			    error: function(XMLHttpRequest, textStatus, errorThrown){
			    	alert("系统错误");
			    }
			});
		},
		//能耗总量统计图
		queryColumn : function() {
			$.ajax({
				url: ctx +'/equipment/energy/getColumn/get.mvc',
			    type:"post", 
			    dataType:'json',
			    data : {
			    	code : $("#analysisCode").val(),
			    	startTime : $("#analysisTimeStart").val(),
			    	endTime : $("#analysisTimeEnd").val(),
			    	operationId : $("#operationAnalysis").val()
			    },
			    success : function(data){
			    	var waterVal = [];
			    	var waterValue = [];
			    	var electricVal = [];
			    	var electricValue = [];
			    	var time=[];
			    	var timeArr=[];
			    	for (var i = 0; i < data.length; i++) {
			    		if (data[i].type == "水表") {
			    			waterVal.push(data[i].value);
			    		}else {
			    			electricVal.push(data[i].value);
			    		}
			    		time.push(data[i].createMonth);
			    	};
			    	for ( var w = 0; w < waterVal.length-1; w++) {
			    		var value;
			    		if (w!=0) {
			    			value = waterVal[w+1] - waterVal[w];
			    			waterValue.push(value);
			    		}else{
			    			waterValue.push(waterVal[0]);
			    		}
					};
					for ( var e = 0; e < electricVal.length-1; e++) {
						var value;
			    		if (e!=0) {
			    			value = electricVal[e+1] - electricVal[e];
			    			electricValue.push(value);
			    		}else{
			    			electricValue.push(electricVal[0]);
			    		}
					};
			    	for ( var j = 0; j < time.length; j++) {
			    		if(timeArr.indexOf(time[j]) == -1){  
			    			timeArr.push(time[j]);  
		                } 
					};
			    	AnalysisInit.drawColumn(waterValue,electricValue,timeArr);
			    },
			    error: function(XMLHttpRequest, textStatus, errorThrown){
			    	alert("系统错误");
			    }
			});
		},
		//用电量工序分摊统计图
		queryElectricPieRate : function() {
			$.ajax({
				url: ctx +'/equipment/energy/getElectricPieRate/get.mvc',
			    type:"post", 
			    dataType:'json',
			    data : {
			    	code : $("#analysisCode").val(),
			    	startTime : $("#analysisTimeStart").val(),
			    	endTime : $("#analysisTimeEnd").val(),
			    	operationId : $("#operationAnalysis").val()
			    },
			    success : function(data){
			    	var valueArr = [];
			    	var nameArr = [];
			    	for ( var i = 0; i < data.length; i++) {
			    		var obj = {'value':data[i].value, 'name':data[i].operationName};
			    		valueArr.push(obj);
			    		nameArr.push(data[i].operationName);
					}
			    	console.log(valueArr);
			    	console.log(nameArr);
			    	// $("#main").remove();
			    	AnalysisInit.drawElectricPieRate(valueArr, nameArr);
			    },
			    error: function(XMLHttpRequest, textStatus, errorThrown){
			    	alert("系统错误");
			    }
			});
		},
		//用水量工序分摊统计图
		queryWaterPieRate : function() {
			$.ajax({
				url: ctx +'/equipment/energy/getWaterPieRate/get.mvc',
			    type:"post", 
			    dataType:'json',
			    data : {
			    	code : $("#analysisCode").val(),
			    	startTime : $("#analysisTimeStart").val(),
			    	endTime : $("#analysisTimeEnd").val(),
			    	operationId : $("#operationAnalysis").val()
			    },
			    success : function(data){
			    	var valueArr = [];
			    	var nameArr = [];
			    	for ( var i = 0; i < data.length; i++) {
			    		var obj = {'value':data[i].value, 'name':data[i].operationName};
			    		valueArr.push(obj);
			    		nameArr.push(data[i].operationName);
					}
			    	console.log(valueArr);
			    	console.log(nameArr);
			    	AnalysisInit.drawWaterPieRate(echarts, valueArr, nameArr);
			    },
			    error: function(XMLHttpRequest, textStatus, errorThrown){
			    	alert("系统错误");
			    }
			});
		},
		//用电量变化趋势图
		queryElectricLineColumn : function() {
			$.ajax({
				url: ctx +'/equipment/energy/getElectricLineColumn/get.mvc',
			    type:"post", 
			    dataType:'json',
			    data : {
			    	code : $("#analysisCode").val(),
			    	startTime : $("#analysisTimeStart").val(),
			    	endTime : $("#analysisTimeEnd").val(),
			    	operationId : $("#operationAnalysis").val()
			    },
			    success : function(data){
			    	var valArr = [];
			    	var valueArr = [];
			    	var valueAddArr = [];
			    	var timeArr = [];
			    	for ( var i = 0; i < data.length; i++) {
			    		valArr.push(data[i].value);
			    		timeArr.push(data[i].createMonth);
					}
			    	for ( var j = 0; j < valArr.length-1; j++) {
						var value;
						value = valArr[j+1]-valArr[j];
						valueArr.push(value);
					}
			    	valueAddArr.push(0);
			    	for ( var k = 0; k < valueArr.length-1; k++) {
			    		var valueAdd;
						valueAdd = valueArr[k+1]-valueArr[k];
						valueAddArr.push(valueAdd);
					}
			    	console.log(valueAddArr);
			    	AnalysisInit.drawElectricLineColumn(echarts,valueArr,valueAddArr,timeArr);
			    },
			    error: function(XMLHttpRequest, textStatus, errorThrown){
			    	alert("系统错误");
			    }
			});
		},
		//用水量变化趋势图
		queryWaterLineColumn : function() {
			$.ajax({
				url: ctx +'/equipment/energy/getWaterLineColumn/get.mvc',
			    type:"post", 
			    dataType:'json',
			    data : {
			    	code : $("#analysisCode").val(),
			    	startTime : $("#analysisTimeStart").val(),
			    	endTime : $("#analysisTimeEnd").val(),
			    	operationId : $("#operationAnalysis").val()
			    },
			    success : function(data){
			    	var valArr = [];
			    	var valueArr = [];
			    	var valueAddArr = [];
			    	var timeArr = [];
			    	for ( var i = 0; i < data.length; i++) {
			    		valArr.push(data[i].value);
			    		timeArr.push(data[i].createMonth);
					}
			    	for ( var j = 0; j < valArr.length-1; j++) {
						var value;
						value = valArr[j+1]-valArr[j];
						valueArr.push(value);
					}
			    	valueAddArr.push(0);
			    	for ( var k = 0; k < valueArr.length-1; k++) {
			    		var valueAdd;
						valueAdd = valueArr[k+1]-valueArr[k];
						valueAddArr.push(valueAdd);
					}
			    	console.log(valueAddArr);
			    	AnalysisInit.drawWaterLineColumn(echarts,valueArr,valueAddArr,timeArr);
			    },
			    error: function(XMLHttpRequest, textStatus, errorThrown){
			    	alert("系统错误");
			    }
			});
		},
		//柱形图
	drawColumn : function(waterValue,electricValue,timeArr){
		var myChart = echarts.init(document.getElementById('main'),'macarons');
        myChart.clear();
		console.log(waterValue);
		console.log(electricValue);
		var maxWaterValue = Math.max.apply(null, waterValue);
		var maxElectricValue = Math.max.apply(null, electricValue);
		var option = {
			color: ['#F0906C','#8FD0F6'],
		    tooltip: {
		        trigger: 'axis',
		        axisPointer: {
		            type: 'cross',
		            crossStyle: {
		                color: '#999'
		            }
		        }
		    },
		    legend: {
		        data:['用电量','用水量']
		    },
		    xAxis: [
		        {
		            type: 'category',
		            data: timeArr,
		            axisPointer: {
		                type: 'shadow'
		            },
		        	name: '时间(年月)'
		        }
		    ],
		    yAxis: [
		        {
		            type: 'value',
		            name: '用电总量',
		            // min: 50,
		            max:maxElectricValue,
		            interval: 50,
		            axisLabel: {
		                formatter: '{value}KWH'
		            }
		        },
		        {
		            type: 'value',
		            name: '用水总量',
		            min: 0,
		            max:maxWaterValue,
		            interval: 20,
		            axisLabel: {
		                formatter: '{value} m³'
		            }
		        }
		    ],
		    series: [
		        {
		        	yAxisIndex:0,
		            name:'用电量',
		            type:'bar',
		            data:electricValue
		        },
		        {
		        	yAxisIndex:1,
		            name:'用水量',
		            type:'bar',
		            data:waterValue
		        }
		    ]
		};
		 myChart.setOption(option);
		},
		//用电量工序分摊统计图
		drawElectricPieRate : function(valueArr, nameArr) {
			var myChart = echarts.init(document.getElementById('main'),'macarons');
			myChart.clear();
			var option = {
				    title : {
				        text: '用电量工序分摊统计图',
				        x:'center'
				    },
				    tooltip : {
				        trigger: 'item',
				        formatter: "{a} <br/>{b} : {c} ({d}%)"
				    },
				    legend: {
				        orient: 'vertical',
				        x: 'left',
				        data: nameArr
				    },
				    series : [
				        {
				            name: '访问来源',
				            type: 'pie',
				            radius : '55%',
				            center: ['50%', '60%'],
				            data: valueArr,
				            itemStyle: {
				                emphasis: {
				                    shadowBlur: 10,
				                    shadowOffsetX: 0,
				                    shadowColor: 'rgba(0, 0, 0, 0.5)'
				                }
				            }
				        }
				    ]
				};
				 myChart.setOption(option);
		},
		//用水量工序分摊统计图
		drawWaterPieRate : function(echarts, valueArr, nameArr) {
			var myChart = echarts.init(document.getElementById('main'),'macarons');
            myChart.clear();
			var option = {
				    title : {
				        text: '用水量工序分摊统计图',
				        x:'center'
				    },
				    tooltip : {
				        trigger: 'item',
				        formatter: "{a} <br/>{b} : {c} ({d}%)"
				    },
				    legend: {
				        orient: 'vertical',
				        x: 'left',
				        data: nameArr
				    },
				    series : [
				        {
				            name: '访问来源',
				            type: 'pie',
				            radius : '55%',
				            center: ['50%', '60%'],
				            data: valueArr,
				            itemStyle: {
				                emphasis: {
				                    shadowBlur: 10,
				                    shadowOffsetX: 0,
				                    shadowColor: 'rgba(0, 0, 0, 0.5)'
				                }
				            }
				        }
				    ]
				};
				 myChart.setOption(option);
		},
		//用电量变化趋势图--折柱混合图
		drawElectricLineColumn : function(echarts,valueArr,valueAddArr,timeArr){
			var myChart = echarts.init(document.getElementById('main'));
            myChart.clear();
			//获取最大值和最小值
			var maxElectricValue = Math.max.apply(null, valueArr);
			var minElectricValue = Math.min.apply(null, valueArr);
			var maxElectricAddValue = Math.max.apply(null, valueAddArr);
			var minElectricAddValue = Math.min.apply(null, valueAddArr);
			if (maxElectricAddValue == minElectricAddValue) {
				maxElectricAddValue = minElectricAddValue+10;
			}
			console.log(maxElectricValue);
			console.log(minElectricValue);
			console.log(maxElectricAddValue);
			console.log(minElectricAddValue);
			var option = {
				color: ['#F0906C','#8FD0F6'],
			    tooltip: {
			        trigger: 'axis',
			        axisPointer: {
			            type: 'cross',
			            crossStyle: {
			                color: '#999'
			            }
			        }
			    },
			    legend: {
			        data:['用电量','用电量增量']
			    },
			    xAxis: [
			        {
			            type: 'category',
			            data: timeArr,
			            axisPointer: {
			                type: 'shadow'
			            }
			        }
			    ],
			    yAxis: [
			        {
			            type: 'value',
			            name: '用电总量',
			            min: 0,
			            max: maxElectricValue,
			            interval: 50,
			            axisLabel: {
			                formatter: '{value} KWH'
			            }
			        },
			        {
			            type: 'value',
			            name: '增量',
			            min: minElectricAddValue,
			            max: maxElectricAddValue,
			            interval: 20,
			            axisLabel: {
			                formatter: '{value} KWH'
			            }
			        }
			    ],
			    series: [
			        {
			            name:'用电量',
			            type:'bar',
			            data:valueArr
			        },
			        {
			            name:'用电量增量',
			            type:'line',
			            yAxisIndex: 1,
			            data:valueAddArr
			        }
			    ]
			};
			myChart.setOption(option);
		},
		//用水量变化趋势图--折柱混合图
		drawWaterLineColumn : function(echarts,valueArr,valueAddArr,timeArr){
			var myChart = echarts.init(document.getElementById('main'),'macarons');
            myChart.clear();
			//获取最大值和最小值
			var maxWaterValue = Math.max.apply(null, valueArr);
			var minWaterValue = Math.min.apply(null, valueArr);
			var maxWaterAddValue = Math.max.apply(null, valueAddArr);
			var minWaterAddValue = Math.min.apply(null, valueAddArr);
			if (maxWaterAddValue == minWaterAddValue) {
				maxWaterAddValue = minWaterAddValue+10;
			}
			var option = {
					color: ['#8FD0F6','#F0906C'],
					tooltip: {
				        trigger: 'axis',
				        axisPointer: {
				            type: 'cross',
				            crossStyle: {
				            }
				        }
				    },
				    legend: {
				        data:['用水总量','用水量增量']
				    },
			    xAxis: [
			        {
			            type: 'category',
			            data: timeArr,
			            position: 'bottom',
			            axisPointer: {
			                type: 'shadow'
			            },
			            name: '时间(年月)'
			        }
			    ],
			    yAxis: [
			        {
			            type: 'value',
			            name: '用水总量',
			            min: 0,
			            max: maxWaterValue,
			            interval: 50,
			            axisLabel: {
			                formatter: '{value} t'
			            }
			        },
			        {
			            type: 'value',
			            name: '增量',
			            min: minWaterAddValue,
			            max: maxWaterAddValue,
			            interval: 20,
			            axisLabel: {
			                formatter: '{value} t'
			            }
			        }
			    ],
			    series: [
			        {
			            name:'用水总量',
			            type:'bar',
			            yAxisIndex: 0,
			            data:valueArr
			        },
			        {
			            name:'用水量增量',
			            type:'line',
			            yAxisIndex: 1,
			            data:valueAddArr
			        }
			    ]
			};
			myChart.setOption(option);
		},
		changeSelect : function() {
			$("#pictureAnalysis").on("change","",function(){
				if ($("#pictureAnalysis").val() == 0) {
					AnalysisInit.queryColumn();
				}
				if ($("#pictureAnalysis").val() == 1) {
					AnalysisInit.queryElectricPieRate();
				}
				if ($("#pictureAnalysis").val() == 2) {
					AnalysisInit.queryWaterPieRate();
				}
				if ($("#pictureAnalysis").val() == 3) {
					AnalysisInit.queryElectricLineColumn();
				}
				if ($("#pictureAnalysis").val() == 4) {
					AnalysisInit.queryWaterLineColumn();
				}
			});
		}
	};
}();


jQuery(document).ready(function() {
    //初始化页面
	AnalysisInit.init();
});

